package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-10
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        // 参数判断,是否都为空
        if (dto == null ||
                (StringUtils.isEmpty(dto.getEquipmentId()) && StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 如果手机号和密码不为空,使用手机号和密码进行登录
        if (!StringUtils.isEmpty(dto.getPhone()) && !StringUtils.isEmpty(dto.getPassword())) {
            // 根据手机号查询用户
            LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(query);
            // 不存在提示用户不存在
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            // 存在的话,取出用户数据库中的salt
            String salt = one.getSalt();
            // 使用用户传入的密码+salt 进行md5 加密
            String pwd = dto.getPassword() + salt;
            String md5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
            // 对比数据库中存储的密码
            // 密码不一致,提示密码错误
            if (!md5.equals(one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 密码一致,使用jwt生成token
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", one.getId());
            String token = AppJwtUtil.getToken(userInfo);
            // 给前端返回对应格式的数据
            ApUser user = new ApUser();
            user.setName(one.getName());
            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        // 如果设备id不为空,使用0来生成token
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", 0);
            String token = AppJwtUtil.getToken(userInfo);
            // 给前端返回对应格式的数据
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService followService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 构建关注表对象
        ApUserFollow follow = new ApUserFollow();
        // 从本地线程获取用户
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        follow.setUserId(user.getUserId());
        ApUser apUser = this.getById(user.getUserId());
        follow.setUserName(apUser.getName());
        // 获取作者对应的user_id
        ResponseResult<ApAuthor> authorResponseResult = articleFeign.getAuthor(dto.getAuthorId());
        if (authorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor author = authorResponseResult.getData();
            follow.setFollowId(author.getUserId());
            follow.setFollowName(author.getName());
        }
        follow.setLevel(1);
        follow.setCreatedTime(new Date());
        // 判断当前登录用户与关注作者是否已经有历史记录
        LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
        query.eq(ApUserFollow::getUserId, user.getUserId());
        query.eq(ApUserFollow::getFollowId, follow.getFollowId());
        ApUserFollow one = followService.getOne(query);
        if (one == null) {
            // 判断如果是关注,新增记录
            if (dto.getOperation() == 0) {
                // 保存关注记录
                followService.save(follow);
            }
        } else {
            // 如果用户操作是取消关注,需要删除对应的记录
            if (dto.getOperation() == 1) {
                followService.remove(query);
            }
        }
        // 发送消息到kafka
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(follow.getFollowId());
        followBehaviorDto.setOperation(dto.getOperation());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        String json = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehaviorTopic, json);
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;
}
